package com.dodol.util;

import com.dodol.common.UserAction;
import com.dodol.testcases.BaseTestObject;
import org.openqa.selenium.WebDriver;
import org.testng.*;

import java.util.*;

/**
 * @Auther: 80736
 * @Date: 2018/9/6 16:03
 * @Description: 用例失败截图机制
 */
public class TestNgListener extends TestListenerAdapter {


    @Override
    public void onTestFailure(ITestResult iTestResult) {
        BaseTestObject bto = (BaseTestObject) iTestResult.getInstance();
        WebDriver driver = bto.getWebDriver();
        try {
            String saveFilePath = UserAction.getScreenShot(driver);
            Reporter.log("测试失败，截图保存到：" + saveFilePath);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFinish(ITestContext iTestContext) {
        Iterator<ITestResult> listOfFailedTests = iTestContext.getFailedTests().getAllResults().iterator();
        while (listOfFailedTests.hasNext()) {
            ITestResult failedTest = listOfFailedTests.next();
            ITestNGMethod method = failedTest.getMethod();
            if (iTestContext.getFailedTests().getResults(method).size() > 1) {
                listOfFailedTests.remove();
            } else {
                if (iTestContext.getPassedTests().getResults(method).size() > 0) {
                    listOfFailedTests.remove();
                }
            }
        }


    }

    private int getId(ITestResult result) {
        int id = result.getTestClass().getName().hashCode();
        id = id + result.getMethod().getMethodName().hashCode();
        id = id + (result.getParameters() != null ? Arrays.hashCode(result.getParameters()) : 0);
        return id;
    }

}
